package com.platform.sys.modular.syncdata.service.impl;

import cn.hutool.db.DbUtil;
import cn.hutool.log.Log;
import org.springframework.stereotype.Service;
import com.platform.core.exception.ServiceException;
import com.platform.sys.modular.syncdata.executor.abs.SyncDataStrategy;
import com.platform.sys.modular.syncdata.executor.factory.SyncDataFactory;
import com.platform.sys.modular.syncdata.mapper.SyncDataTargetMapper;
import com.platform.sys.modular.syncdata.param.SyncDataParam;
import com.platform.sys.modular.syncdata.result.TargetResult;
import com.platform.sys.modular.syncdata.service.SyncDataService;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 要操作其他库的元数据字段配置service接口实现类
 *
 * @author gyp
 * @date 2022-12-04 20:43:04
 */
@Service
public class SyncDataServiceImpl implements SyncDataService {

    private static final Log log = Log.get();

    @Resource
    private SyncDataTargetMapper syncDataTargetMapper;


    @Override
    public void sync(SyncDataParam syncDataParam) {

        /* 1、获取同步目标设置列表 */
        List<TargetResult> targetResults = syncDataTargetMapper.targetBySourceCode(syncDataParam.getCode());
        targetResults.forEach(r ->{
            columns(r,syncDataParam);
        });

    }

    public void columns(TargetResult result,SyncDataParam syncDataParam) {

        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取数据库连接配置
            String dataSourceUrlCurrent = result.getUrl();
            String dataSourceUsernameCurrent = result.getAccount();
            String dataSourcePasswordCurrent = result.getPassword();

            conn = DriverManager.getConnection(dataSourceUrlCurrent, dataSourceUsernameCurrent, dataSourcePasswordCurrent);

            SyncDataStrategy instance = SyncDataFactory.getInstance(result.getStrategy());
            instance.syncData(conn, result, syncDataParam);

        } catch (SQLException | ClassNotFoundException e) {
            log.error(">>> 读取数据库constants配置信息出错：");
            e.printStackTrace();
            throw new ServiceException(1,"数据库连接失败，请检查用户名密码是否正确。");
        } finally {
            DbUtil.close(conn);
        }

    }
}
